package com.java.exer1;

import org.junit.Test;

/**
 * 获取一个字符串在另外一个字符串中出现的次数
 * 例如：“ab”在“abkkcadacabcdab"中出现的次数
 *
 * @author shkstart
 * @create 2021-01-05 22:29
 */
public class StringTest_4 {
    public static void main(String[] args) {
        //自己写的
        String s1 = "abkkcadacabcdab";
        int index = 0;
        int count = 0;
//        System.out.println(s1.length());
        while (true) {
            index = s1.indexOf("ab", index);
            if (index != -1) {
                index += 2;
                count++;
            } else {
                index++;
            }
            if (index == s1.length()) {
                break;
            }
        }
        System.out.println(count);
    }

    //方式二：
    @Test
    public void test1() {
        String s1 = new String("abkkcadacabcdab");
        serch(s1, "ab");
    }

    /**
     * 计算subStr 在 mainStr中出现的次数
     */
    public void serch(String mainStr, String subStr) {
        int mainlength = mainStr.length();
        int sublength = subStr.length();
        int index = 0;
        int count = 0;
        if (mainlength >= sublength) {
            while ((index = mainStr.indexOf(subStr)) != -1) {
                count++;
                mainStr = mainStr.substring(index + sublength);
            }
            System.out.println(count);
        }
    }

    @Test
    public void test2() {
        String s1 = new String("abkkcadacabcdab");
        serch1(s1, "ab");
    }

    public void serch1(String mainStr, String subStr) {
        int mainlength = mainStr.length();
        int sublength = subStr.length();
        int index = 0;
        int count = 0;
        if (mainlength > sublength) {
            while ((index = mainStr.indexOf(subStr, index)) != -1) {
                count++;
                index += sublength;
            }
        }
        System.out.println(count);
    }

}
